import json

import pymysql
from functools import partial
from typing import Callable, Any, Optional
from scheCelery.conf import Config
from celery import shared_task
import requests

conn: Callable[[], pymysql.connections.Connection] = partial(pymysql.connect, host=Config.database['host'],
                                                             port=Config.database['port'],
                                                             user=Config.database['user'],
                                                             password=Config.database['password'],
                                                             db=Config.database['database'])


@shared_task
def flush_route_protect(period: str) -> None:
    header = {
        'Content-Type': 'application/json'
    }
    resp = requests.post(f'{Config.django_backend.get("host")}:{Config.django_backend.get("port")}/system/model/info/',
                         data=json.dumps({"appName": "mainApp", "modelName": "RouteProtect"}), headers=header)
    if resp.status_code != 200:
        raise requests.HTTPError(f'请求失败，状态： {resp.status_code}')
    data = resp.json()
    if data.get('code') != 200:
        raise requests.HTTPError(f'获取信息失败，message: {data["message"]}')

    table_name: str = data['data']['tableName']

    _conn = conn()
    sql_query = "update %s set per_%s = 0 where true;" % (table_name, period)
    with _conn.cursor() as cursor:
        try:
            cursor.execute(sql_query)
            print('执行完成')
        except pymysql.Error as err:
            cursor.rollback()
            raise err
        finally:
            _conn.commit()
            _conn.close()

